package application

import (
	"demo/flutter_server/application/models"
	"demo/flutter_server/domain/authorization"

	"github.com/gofiber/fiber/v2"
	"github.com/rs/zerolog/log"
)

type AuthController struct {
	authorization *authorization.AuthorizationService
}

func NewAuthController(
	authorization *authorization.AuthorizationService,
) *AuthController {
	return &AuthController{
		authorization,
	}
}

func (t *AuthController) Login(c *fiber.Ctx) error {
	loginRequest := new(models.LoginRequest)
	if err := c.BodyParser(loginRequest); err != nil {
		log.Warn().Err(err).Msgf("login params error %v", err)
		return c.JSON(models.Response{
			Code:    models.ResponseParamsError,
			Message: err.Error(),
		})
	}
	user, token, err := t.authorization.Login(loginRequest.Username, loginRequest.Password)
	if err != nil {
		log.Warn().Err(err).Msgf("login error %v", err)
		return c.JSON(models.Response{
			Code:    models.ResponseServerError,
			Message: err.Error(),
		})
	}

	return c.JSON(models.Response{
		Code: models.ResponseSuccess,
		Data: &models.LoginResponse{
			AccessToken: token,
			UserId:      user.ID,
			Nickname:    user.Nickname,
			Avatar:      user.Avatar,
		},
	})
}

func (t *AuthController) RefreshToken(c *fiber.Ctx) error {
	token := c.Get("Authorization")[7:]
	user, token, err := t.authorization.Refresh(token)
	if err != nil {
		log.Warn().Err(err).Msgf("refresh token error %v", err)
		return c.JSON(models.Response{
			Code:    models.ResponseServerError,
			Message: err.Error(),
		})
	}
	return c.JSON(models.Response{
		Code: models.ResponseSuccess,
		Data: &models.LoginResponse{
			AccessToken: token,
			UserId:      user.ID,
			Nickname:    user.Nickname,
			Avatar:      user.Avatar,
		},
	})
}
